package com.sailors.common.task.provider.infra.design.state;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * State factory
 *
 * @description: 状态工厂
 * @author: cyj
 * @date 2022 -09-01 18:24:51
 */
@Component
@Slf4j
public class StateFactory implements ApplicationContextAware {

    /**
     * applicationContext
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        StateFactory.applicationContext = applicationContext;
    }

    /**
     * stateMap
     */
    private static volatile Map<String, IState> stateMap;

    /**
     * Init
     */
    private static synchronized void init() {
        if (null != stateMap) {
            return;
        }
        stateMap = new HashMap<>();
        Map<String, IState> beansOfType = applicationContext.getBeansOfType(IState.class);
        if (null != beansOfType) {
            beansOfType.values().stream().forEach(iState -> stateMap.put(iState.getStateType().getTag(), iState));
        }
    }

    /**
     * Gets instant 获取执行实例
     *
     * @param stateType state type
     * @return the instant
     */
    public static IState getInstant(IState.StateType stateType) {
        if (null == stateMap) {
            init();
        }
        if (!stateMap.containsKey(stateType.getTag())) {
            throw new RuntimeException("未发现：" + stateType);
        }
        return stateMap.get(stateType.getTag());
    }

}
